package com.koalac.ironman.util;

import java.util.Stack;

import android.app.Activity;

public class GBLActivityManager {
	private static Stack<Activity> ACTIVIITY_STACK;
	private static GBLActivityManager INSTANCE;

	private GBLActivityManager() {
	}

	public static GBLActivityManager getActivityManager() {
		if (INSTANCE == null) {
			INSTANCE = new GBLActivityManager();
		}
		return INSTANCE;
	}

	/**
	 * 退出栈顶Activity
	 * @param activity
	 */
	public void popActivity(Activity activity) {
		if (activity != null) {
			/**
			 * 在从自定义集合中取出当前Activity时，也进行了Activity的关闭操作
			 */
			activity.finish();
			if (ACTIVIITY_STACK != null) {
				ACTIVIITY_STACK.remove(activity);
			}
			activity = null;
		}
	}

	/**
	 * 获得当前栈顶Activity
	 * @return
	 */
	public Activity currentActivity() {
		Activity activity = null;
		if (ACTIVIITY_STACK!=null&&!ACTIVIITY_STACK.empty())
			activity = ACTIVIITY_STACK.lastElement();
		return activity;
	}

	/**
	 * 将当前Activity推入栈中
	 * @param activity
	 */
	public void pushActivity(Activity activity) {
		if (ACTIVIITY_STACK == null) {
			ACTIVIITY_STACK = new Stack<Activity>();
		}
		ACTIVIITY_STACK.add(activity);
	}

	/**
	 * 退出栈中所有Activity
	 * @param cls
	 */
	public void popAllActivityExceptOne(Class cls) {
		while (true) {
			Activity activity = currentActivity();
			if (activity == null) {
				break;
			}
			if (cls!=null&&activity.getClass().equals(cls)) {
				break;
			}
			popActivity(activity);
		}
	}
}
